/**
 * 
 */
package com.padbot.qm.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.padbot.qm.util.Md5Encoder;

/**
 * @author Deng
 *
 */
public final class RequestSignFactory {

	private static Logger logger = LoggerFactory.getLogger(RequestSignFactory.class);

	public static String sign(JSONObject params, long currentTime, String appkey, String apptoken) throws Exception {
		logger.debug("params:" + (params == null ? "null" : params.toJSONString()));
		logger.debug("currentTime:" + currentTime);
		logger.debug("appkey:" + appkey);
		logger.debug("apptoken:" + apptoken);
		StringBuilder builder = new StringBuilder();

		if(!params.toString().equals("{}")){
			builder.append(buildParam(params)).append(",");
		}
		builder.append("time:").append(currentTime).append(",");
		builder.append("appkey:").append(appkey).append(",");
		builder.append("apptoken:").append(apptoken);
		return Md5Encoder.encoding(builder.toString()).toString();
	}

	private static String buildParam(JSONObject params) {
		String original = sortParams(params);
		String result = original.substring(1, original.length() - 1);
		return result.replaceAll("\"", "");
	}

	private static String sortParams(JSONObject params) {
		if (params != null) {
			return JSONObject.toJSONString(params);
		}
		return "";
	}

	public static void main(String[] args) throws Exception {
		JSONObject object = JSONObject.parseObject(
				"{\"param1\":\"aaaa\",\"abje\":\"bbbbb\",\"lllll\":\"ccccc\",\"aaaa\":\"23213\",\"2222\":\"2332432\"}");
		sign(object, System.currentTimeMillis(), "111111", "123234werewerw231");
	}
}
